<template>
  <div class="dashboard">
    <!-- 页面标题 -->
    <div class="dashboard-header">
      <h1 class="page-title">仪表盘</h1>
      <el-button type="primary" :icon="Refresh" @click="refreshData" :loading="loading">
        刷新数据
      </el-button>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6" v-for="stat in stats" :key="stat.title">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: stat.color }">
              <el-icon :size="24">
                <component :is="stat.icon" />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-title">{{ stat.title }}</div>
            </div>
          </div>
          <div class="stat-trend">
            <el-icon :color="stat.trend > 0 ? '#67C23A' : '#F56C6C'">
              <component :is="stat.trend > 0 ? ArrowUp : ArrowDown" />
            </el-icon>
            <span :style="{ color: stat.trend > 0 ? '#67C23A' : '#F56C6C' }">
              {{ Math.abs(stat.trend) }}%
            </span>
            <span class="trend-text">较昨日</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :lg="16">
        <el-card title="访问趋势" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>访问趋势</span>
              <el-button-group size="small">
                <el-button :type="chartPeriod === '7d' ? 'primary' : ''" @click="chartPeriod = '7d'">
                  7天
                </el-button>
                <el-button :type="chartPeriod === '30d' ? 'primary' : ''" @click="chartPeriod = '30d'">
                  30天
                </el-button>
                <el-button :type="chartPeriod === '90d' ? 'primary' : ''" @click="chartPeriod = '90d'">
                  90天
                </el-button>
              </el-button-group>
            </div>
          </template>
          <div class="chart-container">
            <div class="chart-placeholder">
              <el-icon :size="48" color="#ddd">
                <TrendCharts />
              </el-icon>
              <p>图表数据加载中...</p>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :lg="8">
        <el-card title="用户分布" shadow="hover">
          <template #header>
            <span>用户分布</span>
          </template>
          <div class="chart-container">
            <div class="chart-placeholder">
              <el-icon :size="48" color="#ddd">
                <PieChart />
              </el-icon>
              <p>图表数据加载中...</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近活动和快捷操作 -->
    <el-row :gutter="20" class="bottom-row">
      <el-col :xs="24" :lg="12">
        <el-card title="最近活动" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最近活动</span>
              <el-link type="primary" @click="viewAllActivities">查看全部</el-link>
            </div>
          </template>
          <el-timeline>
            <el-timeline-item
              v-for="activity in recentActivities"
              :key="activity.id"
              :timestamp="activity.time"
              :type="activity.type"
            >
              <div class="activity-content">
                <div class="activity-title">{{ activity.title }}</div>
                <div class="activity-desc">{{ activity.description }}</div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>

      <el-col :xs="24" :lg="12">
        <el-card title="快捷操作" shadow="hover">
          <template #header>
            <span>快捷操作</span>
          </template>
          <div class="quick-actions">
            <el-button
              v-for="action in quickActions"
              :key="action.name"
              :type="action.type"
              :icon="action.icon"
              class="action-btn"
              @click="handleQuickAction(action.action)"
            >
              {{ action.name }}
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 系统状态 -->
    <el-row :gutter="20" class="system-status-row">
      <el-col :span="24">
        <el-card title="系统状态" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>系统状态</span>
              <el-tag :type="systemStatus.overall === 'healthy' ? 'success' : 'warning'">
                {{ systemStatus.overall === 'healthy' ? '正常' : '警告' }}
              </el-tag>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="8" v-for="status in systemStatus.services" :key="status.name">
              <div class="service-status">
                <div class="service-header">
                  <span class="service-name">{{ status.name }}</span>
                  <el-tag :type="status.status === 'online' ? 'success' : 'danger'" size="small">
                    {{ status.status === 'online' ? '在线' : '离线' }}
                  </el-tag>
                </div>
                <div class="service-metrics">
                  <div class="metric">
                    <span class="metric-label">CPU:</span>
                    <el-progress :percentage="status.cpu" :stroke-width="6" />
                  </div>
                  <div class="metric">
                    <span class="metric-label">内存:</span>
                    <el-progress :percentage="status.memory" :stroke-width="6" />
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  User,
  UserFilled,
  Setting,
  Document,
  ArrowUp,
  ArrowDown,
  TrendCharts,
  PieChart,
  Plus,
  Edit,
  View,
  Refresh
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { dashboardApi } from '@/api'
import type { DashboardStats, AccessTrend, UserDistribution, RecentActivity } from '@/api'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const chartPeriod = ref('7d')

// 统计数据
const stats = ref([
  {
    title: '总用户数',
    value: 0,
    color: '#409EFF',
    icon: UserFilled,
    trend: 0
  },
  {
    title: '活跃用户',
    value: 0,
    color: '#67C23A',
    icon: User,
    trend: 0
  },
  {
    title: '系统配置',
    value: 0,
    color: '#E6A23C',
    icon: Setting,
    trend: 0
  },
  {
    title: '文档数量',
    value: 0,
    color: '#F56C6C',
    icon: Document,
    trend: 0
  }
])

const accessTrends = ref<AccessTrend[]>([])
const userDistribution = ref<UserDistribution[]>([])

// 最近活动
const recentActivities = reactive([
  {
    id: 1,
    title: '用户登录',
    description: '管理员 admin 登录系统',
    time: '2024-01-15 10:30',
    type: 'primary'
  },
  {
    id: 2,
    title: '创建用户',
    description: '新增用户 "张三"',
    time: '2024-01-15 09:15',
    type: 'success'
  },
  {
    id: 3,
    title: '权限更新',
    description: '更新角色 "编辑者" 的权限',
    time: '2024-01-15 08:45',
    type: 'warning'
  },
  {
    id: 4,
    title: '系统备份',
    description: '完成数据库备份',
    time: '2024-01-15 02:00',
    type: 'info'
  }
])

// 快捷操作
const quickActions = reactive([
  {
    name: '新增用户',
    type: 'primary',
    icon: Plus,
    action: 'createUser'
  },
  {
    name: '编辑角色',
    type: 'success',
    icon: Edit,
    action: 'editRole'
  },
  {
    name: '查看日志',
    type: 'info',
    icon: View,
    action: 'viewLogs'
  },
  {
    name: '刷新数据',
    type: 'warning',
    icon: Refresh,
    action: 'refreshData'
  }
])

// 系统状态
const systemStatus = reactive({
  overall: 'healthy',
  services: [
    {
      name: 'Web服务',
      status: 'online',
      cpu: 45,
      memory: 62
    },
    {
      name: '数据库',
      status: 'online',
      cpu: 23,
      memory: 78
    },
    {
      name: '缓存服务',
      status: 'online',
      cpu: 12,
      memory: 34
    }
  ]
})

// 处理快捷操作
const handleQuickAction = (action: string) => {
  switch (action) {
    case 'createUser':
      router.push('/users')
      break
    case 'editRole':
      router.push('/roles')
      break
    case 'viewLogs':
      ElMessage.info('日志功能开发中...')
      break
    case 'refreshData':
      refreshDashboard()
      break
    default:
      ElMessage.info('功能开发中...')
  }
}

// 查看所有活动
const viewAllActivities = () => {
  ElMessage.info('活动日志功能开发中...')
}

// 加载仪表板数据
const loadDashboardData = async () => {
  try {
    loading.value = true
    
    // 获取统计数据
    const statsResponse = await dashboardApi.getStats()
    if (statsResponse.code === 200) {
      const data = statsResponse.data
      stats.value[0].value = data.userCount || 0
      stats.value[0].trend = Math.floor(Math.random() * 20) - 10 // 模拟趋势数据
      stats.value[1].value = data.onlineUserCount || 0
      stats.value[1].trend = Math.floor(Math.random() * 20) - 10
      stats.value[2].value = data.roleCount || 0
      stats.value[2].trend = Math.floor(Math.random() * 20) - 10
      stats.value[3].value = data.permissionCount || 0
      stats.value[3].trend = Math.floor(Math.random() * 20) - 10
    }
    
    // 获取访问趋势数据
    const trendsResponse = await dashboardApi.getAccessTrends(7)
    if (trendsResponse.code === 200) {
      accessTrends.value = trendsResponse.data
    }
    
    // 获取用户分布数据
    const distributionResponse = await dashboardApi.getUserDistribution()
    if (distributionResponse.code === 200) {
      userDistribution.value = distributionResponse.data
    }
    
    // 获取最近活动
    const activitiesResponse = await dashboardApi.getRecentActivities(10)
    if (activitiesResponse.code === 200) {
      recentActivities.splice(0, recentActivities.length, ...activitiesResponse.data)
    }
    
  } catch (error) {
    // 如果API调用失败，使用模拟数据
    console.warn('API调用失败，使用模拟数据:', error)
    stats.value[0].value = 1234
    stats.value[0].trend = 12
    stats.value[1].value = 856
    stats.value[1].trend = 8
    stats.value[2].value = 45
    stats.value[2].trend = -2
    stats.value[3].value = 2567
    stats.value[3].trend = 15
    
    ElMessage.warning('使用模拟数据，请检查后端服务')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = async () => {
  await loadDashboardData()
  ElMessage.success('数据已刷新')
}

// 刷新仪表板数据
const refreshDashboard = () => {
  refreshData()
}

// 组件挂载时加载数据
onMounted(() => {
  loadDashboardData()
})
</script>

<style scoped>
.dashboard {
  padding: 0;
  background-color: #f0f2f5;
  min-height: 100%;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.stats-row {
  margin-bottom: 24px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 8px;
  overflow: hidden;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-title {
  font-size: 14px;
  color: #606266;
}

.stat-trend {
  display: flex;
  align-items: center;
  padding: 0 20px 20px;
  font-size: 12px;
  font-weight: 500;
}

.trend-text {
  margin-left: 4px;
  color: #909399;
}

.charts-row {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  text-align: center;
  color: #909399;
}

.chart-placeholder p {
  margin-top: 12px;
  font-size: 14px;
}

.bottom-row {
  margin-bottom: 24px;
}

.activity-content {
  padding-left: 8px;
}

.activity-title {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.activity-desc {
  font-size: 12px;
  color: #909399;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 12px;
}

.action-btn {
  width: 100%;
  height: 60px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.system-status-row {
  margin-bottom: 24px;
}

.service-status {
  padding: 16px;
  border: 1px solid #EBEEF5;
  border-radius: 8px;
  background: #FAFAFA;
}

.service-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.service-name {
  font-weight: 500;
  color: #303133;
}

.service-metrics {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.metric {
  display: flex;
  align-items: center;
  gap: 8px;
}

.metric-label {
  font-size: 12px;
  color: #606266;
  width: 40px;
}

.metric :deep(.el-progress) {
  flex: 1;
}

@media (max-width: 768px) {
  .dashboard {
    padding: 12px;
  }
  
  .stats-row {
    margin-bottom: 16px;
  }
  
  .charts-row,
  .bottom-row,
  .system-status-row {
    margin-bottom: 16px;
  }
  
  .quick-actions {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>